package com.cskaoyan.typehandler;


import com.cskaoyan.util.JacksonUtil;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@MappedTypes(Integer[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class IntegerArrayTypeHandler implements TypeHandler<Integer[]> {
    // 预编译的SQL语句提供参数的过程

    /**
     * @param ps PreparedStatement对象
     * @param index ？占位符序号
     * @param parameter 提供的值
     * @throws SQLException
     */
    @Override
    public void setParameter(PreparedStatement ps, int index, Integer[] parameter, JdbcType jdbcType) throws SQLException {
        // Integer[] → String
        String str = JacksonUtil.write(parameter);
        ps.setString(index,str);
    }

    // String → Integer[]
    // 从结果集中获取值，转换成set方法能够接受的参数类型
    @Override
    public Integer[] getResult(ResultSet rs, String columnName) throws SQLException {
        String str = rs.getString(columnName);
        Integer[] array = JacksonUtil.read(str, Integer[].class);
        return array;
    }

    @Override
    public Integer[] getResult(ResultSet rs, int columnIndex) throws SQLException {
        String str = rs.getString(columnIndex);
        Integer[] array = JacksonUtil.read(str, Integer[].class);
        return array;
    }

    @Override
    public Integer[] getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String str = cs.getString(columnIndex);
        Integer[] array = JacksonUtil.read(str, Integer[].class);
        return array;
    }
}